#!/usr/bin/env bash

DIR=$(dirname "${BASH_SOURCE[0]}")
FILE="GenshinImpact_Data/Plugins/xlua.dll"
sum=($(md5sum $FILE))

if [ "${sum}" != "ce5877ad4524266636f77817ef7eedb4" ]; then
	# The patch might corrupt invalid/outdated files if this check is skippd.
	echo "Wrong file version or patch is already applied"
	echo "md5sum: ${sum}" && exit 1
fi


# =========== DO NOT REMOVE START ===========
if [[ -e "$DIR/$FILE" ]]; then
	# There is a good reason for this check. Do not pollute the game directory.
	echo "Please move all patch files outside the game directory prior executing."
	echo " -> See README.md for proper installation instructions" && exit 1
fi
# ===========  DO NOT REMOVE END  ===========


if ! command -v xdelta3 &>/dev/null; then
	echo "xdelta3 application is required"
	exit 1
fi

echo "[WARNING] Patch for 1.4.0 to fix a login and runtime crash"
echo ""

# ===========================================================
echo "[WARNING] Hereby you are violating the game's Terms of Service!"
echo "          Do you accept the risk and possible consequences?"
read -p "Accept? [y/n] " choice

if [[ ! "$choice" == [JjSsYy]* ]]; then
	exit 1
fi

echo "--- Applying xLua patch"

# Backup file
mv "$FILE" "$FILE.bak"
xdelta3 -d -s "$FILE.bak" "$DIR/patch_files/xlua_patch.vcdiff" "$FILE"

# Done!
echo "==> Patch applied! Enjoy the game."

exit 0
